import fitz
from pathlib import Path
from PIL import Image, ImageTk
from PyPDF2 import PdfReader, PdfWriter, PdfMerger
from pdf2image import convert_from_path

class PdfUtil():
    def __init__(self, fname=None):
        self.fname = fname

    def getImage(self, num=0):
        num = num - 1
        if num < 0 :
            return
        if self.fname:
            pages = convert_from_path(self.fname)
            pageResize = pages[num].resize((600,int(pages[num].size[1]*600/pages[0].size[0])))
            img = ImageTk.PhotoImage(pageResize)
            return img

    def getPageImg(self, num):
        num = num - 1
        if num < 0:
            return
        if self.fname:
            pdfDocu = fitz.open(self.fname)
            firstPage = pdfDocu[num]
            mat = fitz.Matrix(1, 1)
            pix = firstPage.get_pixmap(matrix=mat)
            img = Image.frombytes('RGB', [pix.width, pix.height], pix.samples)
            nimg= img.resize((600,int(pix.height*600/pix.width)))
            imgTk = ImageTk.PhotoImage(nimg)
            return imgTk
        else:
            return
    def getPage(self):
        if self.fname:
            pdfDocu = fitz.open(self.fname)
            firstPage = pdfDocu[0]
            pSize = firstPage.mediabox_size
            pSize1 = firstPage.mediabox
            mat = fitz.Matrix(0.37, 0.36)
            # mat = fitz.Matrix(0.27, 0.24)
            pix = firstPage.get_pixmap(matrix=mat)
            img = Image.frombytes('RGB', [pix.width, pix.height], pix.samples)
            imgTk = ImageTk.PhotoImage(img)
            return imgTk
        else:
            return

    def merge(self, files, savefile):
        pw = PdfWriter(savefile.name)
        try:
            for f in files:
                pr = PdfReader(f.fname)
                for i in range(0, len(pr.pages)):
                    pw.add_page(pr.pages[i])
        except Exception as e:
            return False
        try:
            with open(savefile.name, 'wb') as pf:
                pw.write(pf)
        except Exception as e:
            return False
        return True

    def merge_new(self, files, savefile):
        pw = PdfMerger()
        for f in files:
            pw.append(f.fname)
        with open(savefile.name, 'wb') as pf:
            pw.write(pf)

    # 按指定的页码范围进行分割
    def split(self, sfname, start, end):
        if self.fname:
            pw = PdfWriter()
            pr = PdfReader(self.fname)
            for i in range(start-1, end):
                pw.add_page(pr.pages[i])
            with open(sfname, 'wb') as pf:
                pw.write(pf)

    # 分割为单页
    def splitPer(self, spath):
        try:
            pr = PdfReader(self.fname)
            path = Path(self.fname)
            name = path.stem
            _spath = Path(spath)
            for i in range(0, len(pr.pages)):
                pw = PdfWriter()
                pw.add_page(pr.pages[i])
                _i = i + 1
                _sname = f'{name}第{_i}页.pdf'
                _fname = _spath / _sname
                with open(str(_fname), 'wb') as pf:
                    pw.write(pf)
            return {'status':True, 'info':'sucess'}
        except Exception as e:
            return {'status':False, 'info':e}

    def getMax(self):
        try:
            pr = PdfReader(self.fname)
            return len(pr.pages)
        except Exception as e:
            return e

        




